//
//  PPMeEditBaseController.m
//  PropertyManage
//
//  Created by Dreamsoul on 15-3-25.
//  Copyright (c) 2015年 com.lab603.mc. All rights reserved.
//

#import "PPMeEditBaseController.h"
#import "PPMeTextView.h"
#import "AFNetWorking.h"
#import "MJExtension.h"
#import "MBProgressHUD+MJ.h"
#import "EGOCache.h"
#import "UserInfo.h"
#import "PPMe.h"
#define Cache_UserInfoKey @"UserInfoCache"
#define CacheTime 24*60*60
@interface PPMeEditBaseController ()<UITextViewDelegate>
@property (nonatomic,weak)PPMeTextView *textView;
//持久化的用户模型
@property (nonatomic,strong)UserInfo *userInfo;
@end

@implementation PPMeEditBaseController
/**
 *  用户模型的懒加载
 */
- (UserInfo *)userInfo{
    if (_userInfo==nil) {
        _userInfo = (UserInfo *)[[EGOCache globalCache] objectForKey:Cache_UserInfoKey];
    }
    return _userInfo;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    if (iOS7) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    self.view.backgroundColor = IWColor(239, 239, 239);
    // 设置导航栏属性
    [self setupNavBar];
    // 添加textView
    [self setupTextView];
    
}
/**
 *  添加textView
 */
- (void)setupTextView
{
    // 1.添加
    PPMeTextView *textView = [[PPMeTextView alloc] init];
    textView.font = [UIFont systemFontOfSize:15];
    textView.frame = CGRectMake(0, 10, self.view.bounds.size.width, 40);
    // 垂直方向上永远可以拖拽
    textView.alwaysBounceVertical = YES;
    textView.delegate = self;
    textView.placeholder = [NSString stringWithFormat:@"请修改您的%@",self.type];
    [self.view addSubview:textView];
    self.textView = textView;
    [self.textView becomeFirstResponder];
    // 2.监听textView文字改变的通知
    [PPNotificationCenter addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:textView];
    
}
/**
 *  监听文字改变
 */
- (void)textDidChange
{
    self.navigationItem.rightBarButtonItem.enabled = (self.textView.text.length != 0);
   
}

- (void)dealloc
{
    [PPNotificationCenter removeObserver:self];
}
/**
 *  设置导航栏属性
 */
- (void)setupNavBar
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(cancel)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(save)];
    self.navigationItem.rightBarButtonItem.enabled = NO;
    self.title = self.type;
}
/**
 *  保存数据
 */
- (void)save
{
    //上传数据
    NSString *urlString = [NSString stringWithFormat:@"%@/%@",BaseUrl,@"user/edit"];
    // AFNetworking\AFN
    // 1.创建请求管理对象
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    // 说明服务器返回的JSON数据
    mgr.responseSerializer = [AFJSONResponseSerializer serializer];
    //2.封装请求参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"userId"] = self.userInfo.ID;
    NSString *postString = @"";
    if ([self.type isEqualToString:@"住址"]) {
        postString = @"room";
    }else if([self.type isEqualToString:@"职业"]){
        postString = @"job";
    }else if([self.type isEqualToString:@"年龄"]){
        postString = @"age";
    }
    params[postString]=@"";
    if ([postString isEqualToString:@"age"]) {
        params[postString] = @([self.textView.text intValue]);
    }else{
        params[postString] = self.textView.text;
    }
    //3.发送请求
    [mgr POST:urlString parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary* responseObject) {
        IWLog(@"-----%@------",responseObject);
        if ([responseObject[@"resultCode"] intValue]==1) {
            //保存数据
            if ([postString isEqualToString:@"age"]) {
                self.userInfo.age = self.textView.text;
            }else if([postString isEqualToString:@"room"]){
                self.userInfo.room = self.textView.text;
            }else if ([postString isEqualToString:@"job"]){
                self.userInfo.job = self.textView.text;
            }
            [[EGOCache globalCache] setObject:self.userInfo forKey:Cache_UserInfoKey withTimeoutInterval:CacheTime];
            [MBProgressHUD showSuccess:@"修改成功"];
            PPMe *me = [[PPMe alloc] init];
            me.userInfo = self.userInfo;
            me.typeString = postString;
            //向block发送消息，更新表单
            if (self.userInfoRefreshBlock) {
                self.userInfoRefreshBlock(me);
            }
            // 关闭控制器
            [self dismissViewControllerAnimated:YES completion:nil];
        }else{
            [MBProgressHUD showError:@"修改失败"];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD showError:@"修改失败"];
    }];

    
    // 关闭控制器
    [self dismissViewControllerAnimated:YES completion:nil];
}

/**
 *  取消
 */
- (void)cancel
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}


@end
